import React from 'react'
import {
  Form,
  Input,
  Row,
  Col,
  Card,
  Select,
  Button,
  Modal,
  Checkbox,
  Radio
} from 'antd'
import { LwjArea }  from 'components'
import FooterToolbar from 'components/FooterToolbar';
import { LwjUpload } from 'components';
import { validateMobile, validatorCharacters } from 'utils/utils';

const FormItem = Form.Item;
const { TextArea } = Input;
const Option = Select.Option;
const formItemLayout = {
  labelCol: {
    span: 5
  },
  wrapperCol: {
    span: 16
  }
};

const UpdateForm = ({
  isUpdate,
  salesmen = [],
  distributors = [],
  saveOrder,
  submitOrder,
  dispatch,
  isFormDirty,
  isLoading,
  setLoading,
  currentOrderDetail = {},
  form: {
    getFieldDecorator,
    validateFieldsAndScroll,
    setFieldsValue,
    getFieldsValue,
  }
}) => {



  const handleSubmit = () => {
    validateFieldsAndScroll((err, values) => {
      if (!err) {
        setLoading(true)
        if (_.isEmpty(values.customerRegion) || values.customerRegion.length !== 3) {
          Modal.info({ title: '提示', content: '请选择客户地址' });
          return;
        }
        if (_.isEmpty(values.consigneeRegion) || values.consigneeRegion.length !== 3) {
          Modal.info({ title: '提示', content: '请选择收货人地址' });
          return;
        }

        if (isUpdate) {
          values.version = currentOrderDetail.version;
        }

        // 组装客户地址数据
        values.customerProvince = values.customerRegion[0];
        values.customerCity = values.customerRegion[1];
        values.customerDistrict = values.customerRegion[2];
        // 组装收货人地址数据
        values.consigneeProvince = values.consigneeRegion[0];
        values.consigneeCity = values.consigneeRegion[1];
        values.consigneeDistrict = values.consigneeRegion[2];

        delete values.customerRegion;
        delete values.consigneeRegion;
        delete values.num;
        saveOrder(values);
      }
    });
  };

  const xlsProps = {
    maxfile: 1,
    target: '/services/upload/order',
    accept: 'image/*,.pdf,.dwg,.dwf,.zip,.rar,.xlsx,.xls',
    uploadIcon: 'upload',
    fileType: '',
    showUploadList: true
  };

  const handleChange = () => {
    dispatch({
      type: 'updateOrder/setFormDirty',
      payload: {
        isFormDirty: true
      }
    });
  }

  const onDistributorsChange = (id) => {
    handleChange()
    dispatch({
      type: 'updateOrder/getSalesmanByDistributor',
      payload: {
        id: id
      }
    });
    setFieldsValue({
      salesmanId: undefined
    })

  }

  const copyCustomerInfo = () => {
    let values = getFieldsValue(['customerName', 'customerPhoneNum', 'customerRegion', 'customerAddress'])
    /** @namespace values.customerAddress */
    setFieldsValue({
      consigneeName: values.customerName,
      consigneePhoneNum: values.customerPhoneNum,
      consigneeRegion: values.customerRegion,
      consigneeAddress: values.customerAddress,
    })
  }

  /** @namespace currentOrderDetail.additionalRemark */
  /** @namespace currentOrderDetail.distributorId */
  return (
    <Form hideRequiredMark>
      <Row>
        <Col span={12}>
          <Card title="基础信息" bordered={false}>
            {isUpdate && <FormItem {...formItemLayout} label="订单编号">
              {getFieldDecorator('num', { initialValue: currentOrderDetail.num })(<Input disabled />)}
            </FormItem>}
            <FormItem {...formItemLayout} label="客户姓名">
              {getFieldDecorator('customerName', {
                rules: [
                  {
                    required: true,
                    message: '客户姓名不能为空',
                    whitespace: true
                  },
                  {
                    max: 5,
                    message: '客户姓名长度不能大于5',
                    whitespace: true
                  }
                  , {
                    validator: validatorCharacters
                  }
                ],
                initialValue: currentOrderDetail.customerName
              })(<Input onChange={handleChange} placeholder="请输入客户姓名" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="客户手机号">
              {getFieldDecorator('customerPhoneNum', {
                rules: [
                  {
                    required: true,
                    message: '请输入客户手机号',
                    whitespace: true
                  }, {
                    validator: validateMobile
                  }
                ],
                initialValue: currentOrderDetail.customerPhoneNum
              })(<Input onChange={handleChange} placeholder="请输入客户手机号" />)}
            </FormItem>
            {(!_.isEmpty(currentOrderDetail.customerRegion) || !isUpdate) && <FormItem {...formItemLayout} label="客户地址">
              {getFieldDecorator('customerRegion', {
                rules: [
                  {
                    required: true,
                    message: '请选择收货人地址',
                    type: 'array'
                  }
                ],
                initialValue: currentOrderDetail.customerRegion
              })(<LwjArea onChange={handleChange} width={'100%'} />)}
            </FormItem>}
            <FormItem {...formItemLayout} label="客户详细地址">
              {getFieldDecorator('customerAddress', {
                rules: [
                  {
                    required: true,
                    message: '请输入客户详细地址',
                    whitespace: true
                  }
                ],
                initialValue: currentOrderDetail.customerAddress
              })(<Input onChange={handleChange} placeholder="请输入客户详细地址" />)}
              <Button onClick={copyCustomerInfo}>复制客户信息</Button>
            </FormItem>

            <FormItem {...formItemLayout} label="收货人姓名">
              {getFieldDecorator('consigneeName', {
                rules: [
                  {
                    required: true,
                    message: '收货人姓名不能为空',
                    whitespace: true
                  },
                  {
                    max: 5,
                    message: '收货人姓名长度不能大于5',
                    whitespace: true
                  }
                  , {
                    validator: validatorCharacters
                  }
                ],
                initialValue: currentOrderDetail.consigneeName
              })(<Input onChange={handleChange} placeholder="请输入收货人姓名" />)}
            </FormItem>

            <FormItem {...formItemLayout} label="收货人手机号">
              {getFieldDecorator('consigneePhoneNum', {
                rules: [
                  {
                    required: true,
                    whitespace: true,
                    message: '请输入客户手机号',
                  }, {
                    validator: validateMobile
                  }
                ],
                initialValue: currentOrderDetail.consigneePhoneNum
              })(<Input onChange={handleChange} placeholder="请输入收货人手机号" />)}
            </FormItem>
            {(!_.isEmpty(currentOrderDetail.consigneeRegion) || !isUpdate) && <FormItem {...formItemLayout} label="收货人地址">
              {getFieldDecorator('consigneeRegion', {
                rules: [
                  {
                    required: true,
                    message: '请选择收货人地址',
                    type: 'array'
                  }
                ],
                initialValue: currentOrderDetail.consigneeRegion
              })(<LwjArea onChange={handleChange} width={'100%'} />)}
            </FormItem>}
            <FormItem {...formItemLayout} label="收货人详细地址">
              {getFieldDecorator('consigneeAddress', {
                rules: [
                  {
                    required: true,
                    message: '请输入收货人详细地址',
                    whitespace: true
                  }
                ],
                initialValue: currentOrderDetail.consigneeAddress
              })(<Input onChange={handleChange} placeholder="请输入收货人详细地址" />)}
            </FormItem>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="销售信息" bordered={false}>
            <FormItem {...formItemLayout} label="门店">
              {getFieldDecorator('distributorId', {
                rules: [
                  {
                    required: true,
                    message: '请选择门店'
                  }
                ],
                initialValue: currentOrderDetail.salesDistributorId
              })(
                <Select
                  onChange={onDistributorsChange}
                  initialValue={currentOrderDetail.salesDistributorId}
                  showSearch
                  placeholder="请选择门店"
                  optionFilterProp="children"
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                >
                  {distributors.map(item => <Option key={item.id} value={item.id}>{item.organizationName}</Option>)}
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="销售员">
              {getFieldDecorator('salesmanId', {
                rules: [
                  {
                    required: false,
                    message: '请选择销售员'
                  }
                ],
                initialValue: currentOrderDetail.salesmanId
              })(
                <Select
                  onChange={handleChange}
                  initialValue={currentOrderDetail.salesmanId}
                  allowClear={true}
                  showSearch
                  placeholder="请选择销售员"
                  optionFilterProp="children"
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
                  {salesmen.map(item => <Option key={item.id} value={item.id}>{item.displayName}</Option>)}
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="意向产品说明">
              {getFieldDecorator('desireProductMemo', {
                rules: [
                  {
                    required: true,
                    message: '请输入意向产品说明',
                    whitespace: true
                  }
                ],
                initialValue: currentOrderDetail.desireProductMemo
              })(<TextArea onChange={handleChange} rows={3} />)}
            </FormItem>
            <FormItem {...formItemLayout} label="参与活动说明">
              {getFieldDecorator('saleEvents', {
                rules: [
                  {
                    required: true,
                    message: '请输入参与活动说明',
                    whitespace: true
                  }
                ],
                initialValue: currentOrderDetail.saleEvents
              })(<TextArea onChange={handleChange} rows={3} />)}
            </FormItem>
            <FormItem {...formItemLayout} label="备注信息">
              {getFieldDecorator('memo', { initialValue: currentOrderDetail.memo })(<TextArea onChange={handleChange} rows={3} />)}
            </FormItem>
            <FormItem {...formItemLayout} label="意向单类型">
              {getFieldDecorator('salesOrderType', {
                rules: [
                  {
                    required: true,
                    message: '请选择意向单类型'
                  }
                ],
                initialValue: currentOrderDetail.salesOrderType
              })(
                <Radio.Group>
                  <Radio.Button value="NORMAL">普通意向单</Radio.Button>
                  <Radio.Button value="PROJECT">工程意向单</Radio.Button>
                </Radio.Group>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="意向产品清单">
              {getFieldDecorator('desireProductsAttachment', {
                rules: [
                  {
                    required: true,
                    message: '请上传意向产品清单'
                  }
                ],
                initialValue: currentOrderDetail.desireProductsAttachment
              })(<LwjUpload multiple={true} onChange={handleChange} {...xlsProps} fileLists={currentOrderDetail.desireProductsAttachment} />)}
            </FormItem>
          </Card>
        </Col>
        <FooterToolbar style={{
          width: '100%'
        }}>
          <Button type="primary" loading={isLoading} onClick={() => handleSubmit()}>
            保存
          </Button>
          {(isUpdate && !isFormDirty) &&
            <Button
              loading={isLoading}
              style={{ marginLeft: 8 }}
              onClick={() => submitOrder()}>提交</Button>}
        </FooterToolbar>
      </Row>
    </Form >
  )
}

export default Form.create()(UpdateForm);
